package com.cse.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cse.entity.ShopType;
import com.cse.mapper.ShopTypeMapper;
import com.cse.service.IShopTypeService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.cse.constants.RedisConstants.CACHE_SHOP_TYPE_KEY;


@RequiredArgsConstructor
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    // 注入StringRedisTemplate
    private  final StringRedisTemplate stringRedisTemplate;
//    private  final IShopTypeService typeService;
    @Override
    public List<ShopType> queryTypeList() {
        // 定义缓存key
        String key = CACHE_SHOP_TYPE_KEY;
        // 从Redis中获取缓存数据
        String shopTypeJson = stringRedisTemplate.opsForValue().get(key);
        // 如果缓存数据不为空
        if (StrUtil.isNotBlank(shopTypeJson)) {
            // 将缓存数据转换为List<ShopType>类型
            List<ShopType> shopTypes = JSONUtil.toList(shopTypeJson, ShopType.class);
            // 返回缓存数据
            return shopTypes;
        }
        // 从数据库中查询数据
        List<ShopType> shoptypeList = query().orderByAsc("sort").list();
        // 判断查询结果为空
        if (shoptypeList.isEmpty()){
            // 返回空集合
            return new ArrayList<>();
        }
        // 将查询结果转换为JSON字符串
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shoptypeList));
        // 返回查询结果
        return shoptypeList;
    }
}
